import Taro from '@tarojs/taro';
import { debounce } from '@/utils/share';

class LoadingManage {
  static loadingCount = 0;

  static loading = false;

  static preventLoading = false;

  static toastWithCallBackOptions = {
    title: '网络连接错误, 请稍后重试',
    mask: true,
    duration: 2000,
    icon: 'none',
  };

  startLoading = () => {
    LoadingManage.loadingCount += 1;
    if (!LoadingManage.loading && !LoadingManage.preventLoading) {
      LoadingManage.loading = true;
      Taro.showLoading({
        title: '加载中...',
        mask: true,
      });
    }
  };

  closeLoading = debounce(() => {
    LoadingManage.loadingCount -= 1;
    if (LoadingManage.loadingCount <= 0 && LoadingManage.loading) {
      Taro.hideLoading();
      LoadingManage.loading = false;
    }
  }, 500);

  toastWithCallBack = (opts: any = {}, callback: undefined | Function, result: any = {}) => {
    LoadingManage.preventLoading = true;
    const options = { ...LoadingManage.toastWithCallBackOptions, ...opts };

    const { ignoreErrorToast, ...rest } = result;

    if (LoadingManage.loading) {
      Taro.hideLoading();
      LoadingManage.loading = false;
    }
    if (!ignoreErrorToast) {
      Taro.showToast(options);
      setTimeout(() => {
        LoadingManage.preventLoading = false;
        typeof callback === 'function' && callback(rest);
      }, options.duration);
    } else {
      LoadingManage.preventLoading = false;
      typeof callback === 'function' && callback(rest);
    }
  };
}

export default new LoadingManage();
